package p.ithorns.framework.common.utils;


import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;

import javax.validation.*;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * ValidateUtil
 * 手动校验
 *
 * @author HtL
 * @date 2024/4/25 10:08
 * @since 1.0.0
 */
public class ValidateUtil {

    private final static Validator VALIDATOR;

    static {
        HibernateValidatorConfiguration validatorConfiguration = Validation
                .byProvider(HibernateValidator.class)
                .configure()
                .failFast(true);

        try (ValidatorFactory validatorFactory = validatorConfiguration.buildValidatorFactory()) {
            VALIDATOR = validatorFactory.getValidator();
        }
    }

    public static void validateThenThrow(Object obj) {
        //解析校验结果
        Set<ConstraintViolation<Object>> validateSet = VALIDATOR.validate(obj);
        if (null != validateSet && !validateSet.isEmpty()) {
            ConstraintViolation<Object> cv = validateSet.iterator().next();
            // Object invalidValue = cv.getInvalidValue();
            String errMsg = MessageFormat.format("参数校验失败: {0}->{1}", cv.getPropertyPath(), cv.getMessage());
            throw new ValidationException(errMsg);
        }
    }

    /**
     * 校验实体，返回实体所有属性的校验结果
     *
     * @param obj -
     * @param <T> -
     * @return Map<String, String>
     */
    public static <T> Map<String, String> validate(T obj) {
        //解析校验结果
        Set<ConstraintViolation<T>> validateSet = VALIDATOR.validate(obj);
        return buildValidationResult(validateSet);
    }

    /**
     * 校验指定实体的指定属性是否存在异常
     *
     * @param obj      -
     * @param property -
     * @param <T>      -
     * @return Map<String, String>
     */
    public static <T> Map<String, String> validateProperty(T obj, String property) {
        Set<ConstraintViolation<T>> validateSet = VALIDATOR.validateProperty(obj, property);
        return buildValidationResult(validateSet);
    }

    /**
     * 将异常结果封装返回
     *
     * @param validateSet -
     * @param <T>         -
     * @return Map<String, String>
     */
    private static <T> Map<String, String> buildValidationResult(Set<ConstraintViolation<T>> validateSet) {
        if (null != validateSet && !validateSet.isEmpty()) {
            Map<String, String> errorMsgMap = new HashMap<>();
            for (ConstraintViolation<T> constraintViolation : validateSet) {
                errorMsgMap.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage());
            }
            return errorMsgMap;
        }
        return new HashMap<>(0);
    }

}